package com.example.concurrency.exercise;

import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: dangwen
 * @createDate: 2021/2/5
 */
public class LockDemo {

    static class MyLockThread implements Runnable{
        int num = 0;
        Lock lock;
        public MyLockThread(Lock lock){
            this.lock = lock;
        }
        @Override
        public void run() {
            lock.lock();
            try {
                Random random = new Random();
                int nextInt = random.nextInt(200);
                Thread.sleep(nextInt);
                num ++;
//                num += (int)Thread.currentThread().getId();
                System.out.println(Thread.currentThread().getName()+" work " + num + " ms "+nextInt);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) {
        Lock lock = new ReentrantLock();
        MyLockThread myLockThread = new MyLockThread(lock);
        for (int i = 0; i < 50; i++) {
//            System.out.println("sum: "+num);
            new Thread(myLockThread).start();
        }
    }
}
